package com.itheima.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.admin.mapper.AdUserMapper;
import com.itheima.admin.pojo.AdUser;
import com.itheima.admin.service.AdUserService;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.util.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper,AdUser> implements AdUserService {
    @Override
    public Map<String, Object> loginCheck(Map<String, String> params) {
        //0获取参数
        String name = params.get("name");
        String password = params.get("password");
        //1.参数校验
        if (StringUtils.isEmpty(name)||StringUtils.isEmpty(password)){
            //1.1为空就返回用户名或密码为空
            throw new LeadNewsException("用户名或密码为空");
        }
        //2.查询数据库
        AdUser adUser = query().eq("name", name).one();
        if (adUser==null) {
            //2.1不存在记录，返回用户名或密码错误
           throw new LeadNewsException("用户名或密码错误");
        }
        //2.2存在记录，校验密码是否一致
        //2.2.1把前端密码加密
        password+=adUser.getSalt();
        String hex = DigestUtils.md5DigestAsHex(password.getBytes());
        //2.2.2比较密码
        if (adUser.getPassword().equals(hex)){
            //3.不一致返回用户名或密码错误
          throw new LeadNewsException("用户名或密码错误");
        }
        //4一致生成token
        String token = AppJwtUtil.createToken(adUser.getId().longValue());

        //5.返回token信息
        adUser.setSalt(null);
        adUser.setNickname(null);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("token",token);
        hashMap.put("user",adUser);
        return hashMap;

    }
}
